import wx
import Image
import os
import pornoganizer

ID_FILE_OPEN = wx.NewId()
ID_FILE_EXIT  = wx.NewId()
ID_NEXT  = wx.NewId()
ID_PREVIOUS  = wx.NewId()
ID_MARK  = wx.NewId()

class ImagePanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.image = None  # wxPython image
        self.marked = False
        self.parent = parent
        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_CHAR(self, self.OnChar)
        
    def display(self, image, marked):
        self.image = image
        self.marked = marked
        self.Refresh(True)

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        if self.image:
            x, y = self.center(self.image)
            dc.DrawBitmap(self.image.ConvertToBitmap(), x, y)
            if self.marked:
                dc.SetTextForeground('GREEN')
                dc.DrawCheckMark(x + 10, y + 10, 20, 20)
            
    def center(self, image):
        imgSize = image.GetSize()
        mySize = self.GetSize()
        x = (mySize.GetWidth() - imgSize.GetWidth())/2
        y = (mySize.GetHeight() - imgSize.GetHeight())/2
        return x, y
            
    def OnChar(self, event):
        keycode = event.GetKeyCode()
        print keycode
        if keycode == 32:
            self.parent.OnNext(event)
        elif keycode == wx.WXK_BACK:
            self.parent.OnPrevious(event)
        elif keycode == 109:
            self.parent.OnMark(event)
        event.Skip()

class mtFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition, wx.Size(500, 400))

        self.iPanel = ImagePanel(self, -1)
        self.im = None  # Magick image

        wx.EVT_CHAR(self, self.OnChar)

        ## Construct "File" menu
        self.menuBar = wx.MenuBar()
        self.menuFile = wx.Menu()
        open = self.menuFile.Append(wx.ID_ANY, "&Open dir","")
        wx.EVT_MENU(self, open.GetId(), self.OnOpen)
        self.menuFile.AppendSeparator()
        file = self.menuFile.Append(wx.ID_ANY, "E&xit", "")
        wx.EVT_MENU(self, file.GetId(),  self.OnExit)
        self.menuBar.Append(self.menuFile, "&File");

        ## next and previous menu
        self.menuFile = wx.Menu()
        next = self.menuFile.Append(wx.ID_ANY, "&Next Image","")
        wx.EVT_MENU(self, next.GetId(), self.OnNext)
        prev = self.menuFile.Append(wx.ID_ANY, "&Previous Image", "")
        wx.EVT_MENU(self, prev.GetId(),  self.OnPrevious)
        self.menuFile.AppendSeparator()
        mark = self.menuFile.Append(wx.ID_ANY, "&Mark Image", "")
        wx.EVT_MENU(self, mark.GetId(),  self.OnMark)
        self.menuBar.Append(self.menuFile, "&Navigate");

        self.SetMenuBar(self.menuBar)
        
        ## prepares structures for image loading
        self.browser = None
        self.loadDir('.')

    def OnNext(self, event):
        if (self.browser.hasNextImg()):
            self.loadImage(self.browser.getNextImg())

    def OnPrevious(self, event):
        if (self.browser.hasPreviousImg()):
            self.loadImage(self.browser.getPreviousImg())
            
    def OnMark(self, event):
        self.browser.toggleImageMark()
        self.iPanel.display(self.im, self.browser.isMarked())
        

    def OnChar(self, event):
        keycode = event.GetKeyCode()
        print keycode
        if keycode == wx.WXK_ESCAPE:
            self.OnExit(event)
        event.Skip()

    def OnOpen(self, event):
        fd = wx.DirDialog(self, "Open Directory", "", wx.OPEN)

        if fd.ShowModal() == wx.ID_OK:
            self.loadDir(fd.GetPath())
            if (self.browser.hasNextImg()):
                self.loadImage(self.browser.getNextImg())
        fd.Destroy()

    def loadDir(self, path):
        self.browser = pornoganizer.ImageBrowser(path)
        
    def loadImage(self, path):
        try:
            source = Image.open(path)
            source = self.resizeImage(source)
            image = apply( wx.EmptyImage, source.size )
            image.SetData( source.convert( "RGB").tostring() )
            # if the image has an alpha channel, you can set it with this line:
            image.SetAlphaData(source.convert("RGBA").tostring()[3::4])
            self.im = image
            self.iPanel.display(self.im, self.browser.isMarked())
        except IOError:
            print "can't open the file"

    def resizeImage(self, image):
        """
        """
        currentSize = self.iPanel.GetSize()
        dummy1, dummy2, imgw, imgh = image.getbbox()
        relative_width = imgw / (1.0 * (currentSize.GetWidth()))
        relative_height = imgh / (1.0 * (currentSize.GetHeight()))
        #print relative_width, relative_height
        new_width = currentSize.GetWidth()
        new_height = currentSize.GetHeight()
        if relative_width > relative_height:
            # resize with
            new_height = imgh/relative_width
        else:
            # resize height
            new_width = imgw/relative_height
        #print new_width, new_height
        return image.resize((int(new_width), int(new_height)), 1)

    ##-----------------------------------------------

    def OnCloseWindow(self, event):
        self.Destroy()

    def OnExit(self, event):
        ret = wx.MessageBox('Are you sure to quit?', 'Question', wx.YES_NO | wx.CENTRE | wx.NO_DEFAULT, self)
        if ret == wx.YES:
            self.Close(True)

#---------------------------------------------------------------------------

class mtApp(wx.App):
    def OnInit(self):
        frame = mtFrame(None, -1, "MagickSimple1")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = mtApp(0)
app.MainLoop()

